<!DOCTYPE html>
<html>
<head>
  <title>一对一聊天</title>
  <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.1/dist/sockjs.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
</head>
<body>
<div>
  <h3>一对一聊天</h3>
  <div id="chat-messages"></div>

  <div>
    <label>接收者:</label>
    <input type="text" id="recipient" placeholder="输入对方用户名">
  </div>

  <div>
    <textarea id="message" rows="4" cols="50" placeholder="输入消息..."></textarea>
  </div>

  <button onclick="sendMessage()">发送</button>
</div>

<script>
  // 建立WebSocket连接
  const socket = new SockJS('/ws');
  const stompClient = Stomp.over(socket);
  let username = null;

  // 连接成功回调
  stompClient.connect({}, function (frame) {
    console.log('Connected: ' + frame);
    username = prompt('请输入您的用户名:');

    // 注册用户
    stompClient.send("/app/chat.register", {},
      JSON.stringify({sender: username, type: MessageType.JOIN}));

    // 订阅个人消息队列
    stompClient.subscribe(`/user/${stompClient.ws._transport.url.split('/')[5]}/queue/messages`, function (message) {
      showMessage(JSON.parse(message.body));
    });
  });

  // 发送消息
  function sendMessage() {
    const recipient = document.getElementById('recipient').value;
    const content = document.getElementById('message').value;

    if (content.trim() && recipient.trim()) {
      stompClient.send("/app/chat.send", {},
        JSON.stringify({
          sender: username,
          recipient: recipient,
          content: content,
          type: MessageType.CHAT
        }));
      document.getElementById('message').value = '';
    }
  }
</script>
</body>
</html>
